package server2;

import server.HttpServlet;
import server.Request;
import server.Response;
import server2.mapper.mapperHost;
import server2.mapper.mappercontext;
import server2.mapper.mapperwrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private mapperHost host;

    public RequestProcessor(Socket socket, mapperHost host) {
        this.socket = socket;
        this.host = host;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            List<mappercontext> contexts = host.getContexts();
           for(mappercontext context :contexts){
               List<mapperwrapper> wrappers = context.getWrappers();
               for(mapperwrapper wrapper:wrappers){
                   String name = wrapper.getName();
                   String url = request.getUrl();
                   String project = url.substring(1,url.length());
                   String path = project.substring(project.indexOf("/"), project.length());

                   if(name.equals(path)){
                       HttpServlet servlet = (HttpServlet) wrapper.getServlet();
                       servlet.service(request,response);
                   }
               }
           }
          /*  // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }*/

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
